package cn.tedu;

import java.sql.*;
import java.util.Scanner;

public class Demo07 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = sc.nextLine();
        System.out.println("请输入密码");
        String password = sc.nextLine();
        //获取连接
        try (Connection conn = DBUtils.getConn()){
//            String sql = "select count(*) from user " +
//                    "where username='"+username+
//                    "' and password='"+password+"'";
//            //创建执行SQL语句对象
//            Statement s = conn.createStatement();
//            //执行查询SQL
//            ResultSet rs = s.executeQuery(sql);
            //使用PreparedStatement避免出现SQL注入漏洞
            String sql = "select count(*) from user " +
                    "where username=? and password=?";
            //预编译的SQL执行对象,将编译SQL语句的时间点从时间点从执行时提前到创建时
            //创建时对SQL语句进行编译将SQL的逻辑锁死,用户输入的内容只能以
            //值的形式添加到原SQL语句中,这样原有SQL语句的逻辑部分不会被
            //用户输入的内容所改变,从而解决了SQL注入的问题
            PreparedStatement ps = conn.prepareStatement(sql);
            //替换?的值
            ps.setString(1,username);
            ps.setString(2,password);
            //执行查询
            ResultSet rs = ps.executeQuery();

            //让游标往下移动一格,成功失败都会有数据,所以不需要判断
            rs.next();
            int count = rs.getInt(1);
            if (count>0){
                System.out.println("登录成功!");
            }else{
                System.out.println("用户名或密码错误");
            }
            //漏洞:select * from user where username=asdf and password='or'1'='1
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
}
